package jee.demo.pro.controller;

import jee.demo.pro.model.User;
import jee.demo.pro.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by Zhen on 2015/4/17.
 */
@Controller
public class UserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping(value = {"login", "register"}, method = RequestMethod.GET)
    public void defaults() {
        LOGGER.debug("Execute GET: login|register");
    }

    @RequestMapping(value = "logout")
    public String logout(User o,  BindingResult results,
                         HttpSession session) {
        String username = (String) session.getAttribute("loginUser");
        if (username != null) {
            //need o.username
            o.setUsername(username);
            userService.logout(o);
        }
        session.invalidate();
        return "";
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(User o) {
        LOGGER.debug("Execute POST: login");

        return userService.login(o);
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String register(User o) {
        LOGGER.debug("Execute POST: register");

        return userService.register(o);
    }

}
